package binary_tree.leetcode.medium;

/**
 * @author bruin_du
 * @description 实现前缀树
 * @date 2022/8/17 23:50
 **/
public class OfferII062_Trie {
    TreeNode root;
    class TreeNode {
        TreeNode[] next;
        boolean isEnd;

        public TreeNode() {
            next = new TreeNode[26];
            isEnd = false;
        }
    }
    /** Initialize your data structure here. */
    public OfferII062_Trie() {
        root = new TreeNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TreeNode cur = root;
        char[] arr = word.toCharArray();
        for (char ch : arr) {
            int index = ch - 'a';
            if (cur.next[index] == null) {
                cur.next[index] = new TreeNode();
            }
            cur = cur.next[index];
        }
        cur.isEnd = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TreeNode cur = searchPrefix(word);
        return cur != null && cur.isEnd;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    TreeNode searchPrefix(String prefix) {
        char[] arr = prefix.toCharArray();
        TreeNode cur = root;
        for (char ch : arr) {
            int index = ch - 'a';
            if (cur.next[index] == null) return null;
            cur = cur.next[index];
        }
        return cur;
    }
}
